/**
 * Copyright (c) 2009 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.ContextUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.SessionFactory;
import org.hibernate.impl.SessionFactoryImpl;


/**
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/SystemAction")
public class SystemAction extends BaseAction{
	
	private static final long serialVersionUID = -2611970074407296214L;
	private static Log log = LogFactory.getLog(SystemAction.class);
	
	private DynaBeanManager dynaBeanManager;
	
	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}

	@Action(value="prepareClearSecondCache",
			results={@Result(name="success", location="/admin/system/clearSecondCache.jsp")}
	)
	public String prepareClearSecondCache() throws Exception {
		JSONArray jsonArray = new JSONArray();	
		SessionFactoryImpl sessionFactory = (SessionFactoryImpl) ContextUtil.getAc().getBean("sessionFactory");
		Map map = sessionFactory.getAllSecondLevelCacheRegions();
		Iterator it = map.keySet().iterator();
		while(it.hasNext()){
			Object key = it.next();
			
			if(key.equals("org.hibernate.cache.StandardQueryCache")||key.equals("org.hibernate.cache.UpdateTimestampsCache"))
				continue;
			JSONObject jsonObj = new JSONObject();
			jsonObj.element("className", key);
			jsonArray.add(jsonObj);
		}
				
		this.json = jsonArray.toString();
		
		return SUCCESS;
	}
	
	@Action(value="clearSecondCache")
	public String clearSecondCache() throws Exception {
		JSONObject jsonObj = new JSONObject();
		try{
			String[] names = this.json.split(",");
			List<String> entities = Arrays.asList(names);
			dynaBeanManager.clearSecondCache(entities);
			jsonObj.element("success", true);
			jsonObj.element("reason", "操作成功!");
			this.json = jsonObj.toString();
		}catch(Exception e){
			jsonObj.element("success", false);
			jsonObj.element("reason", e.getMessage());
			this.json = jsonObj.toString();
		}
		
		return AJAX;		
	}
}
